<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Aliyun\DySDKLite\Iot;
use App\Models\Dataplan;
use App\Models\Order;
use App\Models\Card;
use EasyWeChat;
use EasyWeChat\Factory;
use Log;
use function EasyWeChat\Kernel\Support\generate_sign;

class IndexController extends Controller
{
    public function login(Request $request)
    {
        return view('front.login');
    }

    public function loginDo(Request $request)
    {
        $rs['status'] = 'warning';

      
        $iccid = $this->findNum($request->iccid);

        if( empty($iccid) ||strlen($iccid)!=19 ){           
            $rs['msg'] = '卡号错误';
            return back()->with('rs',$rs);
        }
        //dd($iccid);
        $wechat_user =  session('wechat.oauth_user.default');
     //dd($wechat_user);
        $data = $this->getUserInfo($wechat_user->id);
        $data['openid'] = $wechat_user->id; 
        $data['iccid']  = $iccid;
        $user = Card::where(['iccid'=>$iccid])->first();
        if($user) {
           Card::where(['iccid'=>$iccid])->update($data);
        } else { 

            $user = Card::create($data);
        }
          
        
        if($user) {
            session(['user'=>$user]);
           
            return redirect('/');
        } 
        $rs['msg'] = '流量卡号不存在';
        return back()->with('rs',$rs);

        
    }

    public function logout(Request $request)
    {
        $request->session()->forget('user');
        return redirect('login');
    }

    public function index()
    {
        return view('front.index');
    }

    /**
     * 查询流量
     */
    public function queryFlow(Request $request)
    {
        $iccid = session('user')->iccid;
        $data = [];
        $rs = Iot::queryCardFlowInfo($iccid);

       //dd($rs);
        $data = [];
        if($rs->Code=='OK') {
            $list = $rs->CardFlowInfos->CardFlowInfo;
            foreach ($list as $key => $info) {
                //dd($info);
                $data[$key]['name']  = $info->ResName;
                $data[$key]['total'] = round($info->FlowResource/1024,2).' MB';
                $data[$key]['used']  = round($info->FlowUsed/1024,2).' MB';
                $data[$key]['reset'] = round($info->RestOfFlow/1024,2).' MB';
                $data[$key]['validDate']  = $info->ValidDate;
                $data[$key]['expireDate'] = $info->ExpireDate;
            }
            
        }
        return view('front.query',compact('data'));
    }

    /**
     * 套餐列表
     */
    public function offerDtl()
    {
        $iccid = session('user')->iccid;
        $rs    = Iot::queryIotCardOfferDtl($iccid);
        //dd($rs);
        $data = [];
        // if($rs['status']==true) {
        //     $offerids = array_keys($rs['data']);
        //     $data = Dataplan::whereIn('offerid',$offerids)->get();
            
        // }

        $data = Dataplan::get();
        $user['openid'] = session('wechat.oauth_user.default')->id;
        $user['iccid']  = $iccid;
        return view('front.offerdtl',compact('data','user'));
    }

    /**
     * 充值记录
     */
    public function log(Request $request)
    {
        $list = Order::orderBy('id','desc')
                        ->where('status',2)
                        ->paginate(10);
        return view('front.log',compact('list'));
    }

    public function makeOrder(Request $request)
    {
        $rs['status'] = false;
        $rs = (array)Iot::queryCardStatus($request->iccid);

        if($rs['Code']!=='OK') {
            $rs['msg'] = 'IccId对应的卡资源不存在';
             return response()->json($rs);
        }
      
        $code = date('YmdHis').mt_rand(1000,9999);
       
        
        try {
            
            $data['openid']      = $request->openid;
            $data['iccid']       = $request->iccid;
            $data['dataplan_id'] = $request->dataplan_id;
            $data['price']       = $request->price;
            $data['num']         = $request->num;
            $data['code']        = $code;
            $flag = Order::create($data);
            if($flag) {
              $time = time();
                $app = app('wechat.payment');
                $result = $app->order->unify([
                    'body' => '远程摄像头',
                    'out_trade_no' => $code,
                    'total_fee'    => (int)$request->price,               
                    'trade_type' => 'JSAPI',
                    'openid' => $request->openid,
                    'timeStamp' => $time,
                ]);
              Log::info(json_encode($result));
                // 如果成功生成统一下单的订单，那么进行二次签名
                if ($result['return_code'] === 'SUCCESS') {
                    // 二次签名的参数必须与下面相同
                    $params = [
                        'appId'     => config('wechat.official_account.default.app_id'),
                        'timeStamp' => $time,
                        'nonceStr'  => $result['nonce_str'],
                        'package'   => 'prepay_id='.$result['prepay_id'],
                        'signType'  => 'MD5',
                    ];
                    // config('wechat.payment.default.key')为商户的key
                    $params['paySign'] = generate_sign($params, config('wechat.payment.default.key'));
                    $params['signJs'] = $result['sign'];
                    $params['order_code']    = $code;
                    $params['appId'] = config('wechat.official_account.default.app_id');
                    $params['order_created'] = date('Y-m-d H:i:s');
                    $params['total_fee'] = (int)$request->price;
                    //$params['key'] =config('wechat.payment.default.key');
                    $rs['data'] = $params;
                    $rs['status'] = true;
                    
                    return response()->json($rs);
                }
                $rs['data'] = $result;
                $rs['status'] = true;
                return response()->json($rs);  
            
  
            } 
            $rs['msg'] = '保存订单失败';
            return response()->json($rs);    
        } catch (\Exception $e) {
            $rs['msg'] = $e->getMessage();
            return response()->json($rs);
        }
        $rs['msg'] = '充值是失败';
        return response()->json($rs);
        

        
       
    }

    /**
     * 扫码支付
     */
    public function schemeCode(Request $request)
    {
        $rs['status'] = false;
        $config = config('wechat.payment.default');     
        $app = Factory::payment($config);
        
        $message['dataplan_id'] = $request->dataplan_id;
        $message['price']   = $request->price;
        $message['openid']  = $request->openid;
        Log::info(json_encode($message));
       
        $result = $app->order->unify([
            'body' => '远程摄像头',
            'out_trade_no' => date('YmdHis').mt_rand(1000,9999),
            'trade_type'   => 'NATIVE',
            'product_id'   => $message['dataplan_id'], // $message['product_id'] 则为生成二维码时的产品 ID
            'total_fee'    => (int)$message['price'],
            'openid'       => $message['openid'],               
        ]); 
        Log::info(json_encode($result));
        if($result) {
            $rs['status'] = true;
            $rs['data'] =  $result['code_url'];
            return response()->json($rs);
        }           
        
               
        return response()->json($rs);
    }

    public function payNotify()
    {
        $config = config('wechat.payment.default');     
        $app = Factory::payment($config);
        Log::info('进入回调：');
        $response = $app->handlePaidNotify(function($message, $fail){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单

            $order = Order::where(['code'=>$message['out_trade_no']])->first();

            if (!$order || $order->pay_time) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

           

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    if(array_get($message,'total_fee')!=$order->price) {
                        Log::info('微信回调订单金额'.array_get($message,'total_fee').'与系统中的订单金额.'.$order->price.'数据不一致');
                        return false;
                    }
                    $order->pay_time = array_get($message,'time_end'); // 更新支付时间为当前时间
                    $order->status = '2';

                    $order->transaction_id = array_get($message,'transaction_id');

                // 用户支付失败
                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = '0';
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

            $order->save(); // 保存订单
            // 给用户冲流量
            $iccid   = $order->iccid;
            $offerid = object_get($order,'dataplan.offerid');
            $effcode = 'AUTO_ORD';
            if($order->dataplan_id==2) {
                $effcode = 1000;
            }
            if((int)$order->num>1) {
               for($i=0;$i<$order->num;$i++) {
                Iot::doIotRecharge($iccid,$offerid,$effcode);  
               }
               
            } else {
                Iot::doIotRecharge($iccid,$offerid,$effcode);
            }
            

            

           
            return true; // 返回处理完成
        });

        $response->send(); // return $response;
    }


    private  function getUserInfo($openid)
    {
        $app = app('wechat.official_account');
        $userInfo = $app->user->get($openid);
     // dd($userInfo);
        $data['nickname'] = array_get($userInfo,'nickname');
        $data['avatar']   = array_get($userInfo,'headimgurl');
        return $data;
    } 

    private  function findNum($str='')
    {
        $str=trim($str);
        if(empty($str)){return '';}
        $temp=array('1','2','3','4','5','6','7','8','9','0');
        $result='';
        for($i=0;$i<strlen($str);$i++){
            if(in_array($str[$i],$temp)){
                $result.=$str[$i];
            }
        }
        return $result;
    }


    public function test()
    {
         $iccid = '8986031848206552926';
         $rs    = Iot::queryIotCardOfferDtl($iccid);

        $data = [];
        if($rs->Code=='OK') {
            $list = $rs->CardFlowInfos->CardFlowInfo;
            // dd($list);
            foreach ($list as $key => $info) {
                //dd($info);
                $data[$key]['name']  = $info->ResName;
                $data[$key]['total'] = round($info->FlowResource/1024,2).' MB';
                $data[$key]['used']  = round($info->FlowUsed/1024,2).' MB';
                $data[$key]['reset'] = round($info->RestOfFlow/1024,2).' MB';
                $data[$key]['validDate']  = $info->ValidDate;
                $data[$key]['expireDate'] = $info->ExpireDate;
            }
            
        }
        
    }
}
